package com.yjps.system.service;

import com.yjps.common.page.Pager;
import com.yjps.system.dao.DemandDao;
import com.yjps.system.model.Demand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jessy on 2015/8/25.
 */
@Service
public class DemandService {
    Logger log = LoggerFactory.getLogger(DemandService.class);

    @Autowired
    DemandDao demandDao;

    public int save(Demand demand){
        return demandDao.save(demand);
    }

    public Demand getDemand(int id){
        return demandDao.load(id);
    }

    public void updateDemand(Demand demand){
        String hql = "update Demand d set d.demandType =:demandType,d.demandState =:demandState,d.houseType =:houseType,d.houseCounty =:houseCounty,d.houseTown =:houseTown,d.housePrice =:housePrice,d.houseArea =:houseArea,d.acceptTime =:acceptTime,d.acceptResult =:acceptResult" +
                " where d.id =:id";
        Map<String, Object> map = new HashMap<>();
        map.put("demandType",demand.getDemandType());
        map.put("demandState",demand.getDemandState());
        map.put("houseType",demand.getHouseType());
        map.put("houseCounty",demand.getHouseCounty());
        map.put("houseTown",demand.getHouseTown());
        map.put("housePrice",demand.getHousePrice());
        map.put("houseArea",demand.getHouseArea());
        map.put("acceptTime",demand.getAcceptTime());
        map.put("acceptResult",demand.getAcceptResult());
        map.put("id",demand.getId());
        demandDao.excute(hql, map);
    }

    public Pager<Demand> getDemandByPager(Pager<Demand> pager,String acceptResult) throws Exception {
        Map<String, Object> params = new HashMap<>();
        String queryString = "from Demand t where t.isValid = 1";
        if(!StringUtils.isEmpty(acceptResult)) {
            queryString += " and t.acceptResult =:acceptResult";
            params.put("acceptResult", Integer.parseInt(acceptResult));
        }
        queryString += " order by t.id desc";
        List<Demand> accounts = demandDao.findWithSelect(queryString, params, (pager.getPageNo()-1)*pager.getPageSize(), pager.getPageSize());
        pager.setCount(demandDao.getTotalCount(queryString, params));
        pager.setList(accounts);
        return pager;
    }

    public  void  delete(int id){
        demandDao.invalid(demandDao.load(id));
    }
}
